
import { jwtVerify, SignJWT } from 'jose';
import { redirect } from 'next/navigation'
import { cookies } from 'next/headers';
export type Session = {
  user: {
    id: string;
    name: string;
  };
  accessToken: string;
  refreshToken: string
};

const secretKey = process.env.SECRET_KEY || "secret";
const encodeKey = new TextEncoder().encode(secretKey);
export async function createSession(paylod: Session) {
  const expiredAt = new Date(Date.now() + 60 * 60 * 24 * 7 * 1000);

  const session = await new SignJWT(paylod).setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt().setExpirationTime("7d").sign(encodeKey)
  const cookieStore = await cookies()
  cookieStore.set('session', session, {
    httpOnly: true,
    secure: true,
    expires: expiredAt,
    sameSite: 'lax',
    path: '/'
  })
}

export async function getSession() {
  const cookieStore = await cookies()
  const cookie = cookieStore.get('session')?.value
  if (!cookie) {
    return null
  }

  try {
    const { payload } = await jwtVerify(
      cookie,
      encodeKey,
      {
        algorithms: ["HS256"],
      }
    );
    return payload as Session
  } catch (error) {
    console.log("failed to verify the session",error);
  }

  redirect('/auth/sigin')
}

export async function deleteSession() {
  const cookieStore = await cookies()
  cookieStore.delete('session')
}

export async function updateTokens({ accessToken,refreshToken }:{accessToken:string,refreshToken:string}){
  console.log('刷新token222')
  const cookieStore = await cookies()
  const cookie = cookieStore.get('session')?.value
  if(!cookie){
    return null
  }
  const { payload } = await jwtVerify<Session>(
    cookie,
    encodeKey,
  );
  if(!payload){
    throw new Error("无可用session")
  }
  const newPayload:Session = {
    user:{
      ...payload.user,
    },
    accessToken,
    refreshToken
  }

  await createSession(newPayload)
 }